package com.tianjipms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianjipms.dto.UserVehicleDTO;
import com.tianjipms.entity.Vehicle;
import com.tianjipms.service.VehicleService;
import com.tianjipms.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/vehicle")
public class VehicleController {
    @Resource
    private VehicleService vehicleService;
    //添加车牌
    @PostMapping("/add")
    public Result addVehicle(@RequestBody Vehicle vehicle){
        return Result.ok(vehicleService.save(vehicle));
    }
    //绑定车牌
    @PostMapping("/binding")
    public Result bindingLicenseNumber(@RequestBody UserVehicleDTO vehicleDTO){
        if(vehicleService.existsByLicenseNumber(vehicleDTO.getLicenseNumber())){
            return vehicleService.updateUserByLicenseNumber(vehicleDTO);
        }else {
            Vehicle vehicle = new Vehicle();
            vehicle.setUserId(vehicleDTO.getUserId());
            vehicle.setLicenseNumber(vehicleDTO.getLicenseNumber());
            vehicle.setIsVip(0);
            vehicleService.save(vehicle);
        }
        return Result.ok();
    }
    //查询车辆信息
    @GetMapping("/search")
    public Result searchVehicl(String licenseNumber){
        return Result.ok(vehicleService.findVehiclByLicenseNumber(licenseNumber));
    }
    //删除车牌
    @DeleteMapping("/delete/{id}")
    public Result deleteVehicl(@PathVariable Long id){
        return Result.ok(vehicleService.removeById(id));
    }

    //分页查询所有车辆信息
    @GetMapping("/listAll")
    public Result listAll(@RequestParam(defaultValue = "1") Long pageNum,
                          @RequestParam(defaultValue = "5") Long pageSize){
        IPage<Vehicle> page = new Page<>(pageNum, pageSize);
        vehicleService.page(page);
        return Result.ok(page);
    }

    //分页条件查询车辆信息
    @GetMapping("/list")
    public Result listByUserId(@RequestParam("userId") Long userId,
                               @RequestParam(defaultValue = "1") Long pageNum,
                               @RequestParam(defaultValue = "5") Long pageSize){
        IPage<Vehicle> page = new Page<>(pageNum, pageSize);
        vehicleService.findVehiclListByPage(page,userId);
        return Result.ok(page);
    }
}
